<?php
namespace PhpBoot\Cache;

use PhpBoot\Utils\Logger;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

/**
 * 检查缓存版本是否过期
 * @author gaoolp
 */
class VersionChecker
{

    /**
     * 缓存版本
     * 固定使用文件缓存，发版时更新版本，写入文件
     * @var string
     */
    private $version = '';
    private $key = 'app.cache.version';

    function __construct(){
        if ($version = $this->getVersion()) {
            $this->version = $version;
        } else {
            $this->createNewVersion();
        }
    }
    /**
     * 判断是否过期
     * @param mixed $data 从缓存中得到的数据
     * @param int $createdTime
     * @return boolean
     */
    public function __invoke($data, $createdTime){
        return $this->version >= $this->getVersion();
    }

    public function createNewVersion()
    {
        $version = time();
        $this->version = $version;
        $this->getCache()->set($this->key, $version);
    }
    private function getCache()
    {
        // Logger::info('cacheVersionPath: ' . dirname(__FILE__) . '/Runtime/');
        return new CheckableCache(new FilesystemAdapter('', 0, dirname(__FILE__) . '/Runtime/'));
    }
    private function getVersion()
    {
        // Logger::info('getVersion: ' . $this->getCache()->get($this->key));
        return $this->getCache()->get($this->key);
    }
}
